package com.wgchao.amc.common;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: JWTUtil
 * @author: wgchao
 * @createTime: 2019/8/30 5:38 PM
 * @Description: JWT工具类
 */
public class JWTUtil {
    public static String SECRET = "wgchao-secret";//秘钥



    public static String createToken(String userId) throws Exception {
        //签发时间
        Date istDate = new Date();

        //设置过期时间
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.MINUTE, 3000);
        Date expiresDate = nowTime.getTime();

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");

        String token = JWT.create()
                .withHeader(map)
                .withClaim("userId", userId)
                .withExpiresAt(expiresDate)
                .withIssuedAt(istDate)
                .sign(Algorithm.HMAC256(SECRET));

        return token;
    }


    public static String verifyToken(String token, String key) throws Exception{
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        DecodedJWT jwt = null;
        try {
            jwt = verifier.verify(token);
        } catch (Exception e) {
            jwt = null;
        }
        if(jwt == null){
            return null;
        }
        return jwt.getClaims().get(key).asString();
    }



    public static void main(String[] args) throws Exception {
        String token = JWTUtil.createToken("1");

        System.out.println(token);
        //正常测试
        String asString = JWTUtil.verifyToken(token, "userId");
//        String asString = verifyToken.get("userId").asString();
        System.out.println(asString);

        //过期测试
        token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NjcxNjAwMzQsInVzZXJJZCI6IjEiLCJpYXQiOjE1NjcxNTgyMzR9.qKcykyTwU5Snb3udBWeSUWxWCeZU7o2d8bbosC2TlmM";
        //Map<String, Claim> verifyToken2 = JWTUtil.verifyToken(token);
    }
}
